package com.baoyang.tool.utils;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多级代理的IP列表：分割后去除每个IP的首尾空格
        if (ip != null && ip.contains(",")) {
            String[] ips = ip.split(",");
            for (int i = 0; i < ips.length; i++) {
                ips[i] = ips[i].trim(); // 关键修改：逐项调用trim()
            }
            ip = ips[0]; // 通常取第一个非代理IP
        }
        return ip;
    }

}
